package com.helwen.tools.zhijiang;

import org.apache.poi.xwpf.usermodel.*;
import org.junit.jupiter.api.Test;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * 读取word，  只是读取国标中的word固定文件。  拼成将xml格式参数转成json参数，去调东软件平台将枝江数据上传到宜昌平台中。
 * 生成建表sql 与xml形式
 * @author Christmas_G
 *
 */
public class findWordPrimeKeyFile {
    @Test
    public void readWordCreateSql() throws FileNotFoundException, IOException {


        try {
            //String filepath="C:\\develop\\docs\\枝江\\宜昌市一体化全民健康信息平台接口文档\\医疗";
            //String filepath="D:\\123\\全民健康\\医疗\\EMR";
            //String filepath="D:\\123\\全民健康\\医疗\\HIS及其他";
            //String filepath="D:\\123\\全民健康\\医疗\\EMR";
            //String filepath="D:\\123\\全民健康\\医疗\\HIS及其他";
            String filepath="D:\\123\\全民健康\\公共卫生";
            File file=new File(filepath);//文件夹
            String[] filelist = file.list();
            String filePath2="C:\\develop\\docs\\template\\primeKey.txt";
            File file2=new File(filePath2);
            FileOutputStream fileOutputStream = new FileOutputStream(file2);
            OutputStreamWriter osw = new OutputStreamWriter(fileOutputStream, "UTF-8");

            for (int i = 0; i < filelist.length; i++) {
                String filename = filelist[i];
                File readfile = new File(filepath + "\\" + filename);
                if(filename.startsWith("~")){
                    continue;
                }
                XWPFDocument document = new XWPFDocument(new FileInputStream(readfile));
                // 获取word中的所有段落与表格
                List<IBodyElement> elements = document.getBodyElements();
                String protocol="";
                for (IBodyElement element : elements) {
                    // 段落
                    if (element instanceof XWPFParagraph) {
                        String str= getTableCellText((XWPFParagraph) element);
                        if(str!=null && str.length()>1){
                            protocol=str;
                        }

                    }else if(element instanceof XWPFTable){
                        String explaintable="";
                        if(protocol!=null && !protocol.equals("")) {
                            if (protocol.indexOf("表名：") > 0) {
                                String[] farr = protocol.split("表名：");
                                protocol = farr[1];
                                explaintable = farr[0];
                            } else if (protocol.indexOf("表名:") > 0) {
                                String[] farr = protocol.split("表名:");
                                protocol = farr[1];
                                explaintable = farr[0];
                            } else if (protocol.indexOf("表:") > 0) {
                                String[] farr = protocol.split("表:");
                                protocol = farr[1];
                                explaintable = farr[0];
                            } else if (protocol.indexOf("表：") > 0) {
                                String[] farr = protocol.split("表：");
                                protocol = farr[1];
                                explaintable = farr[0];
                            } else if (protocol.indexOf("表") > 0) {
                                String[] farr = protocol.split("表");
                                protocol = farr[1];
                                explaintable = farr[0];
                            }
                        }
                        protocol=getRealField(protocol);
                        explaintable=getRealField(explaintable);
                        String res=getTabelText((XWPFTable) element,explaintable,protocol);

                        String ss="alter table "+protocol+" add constraint "+protocol+"_KEYS primary key ("+res+");  --"+explaintable;
                        osw.write("delete from "+protocol+";");
                        osw.write("\r\n");
                        osw.write(ss);
                        osw.write("\r\n");
                        osw.write("\r\n");
                    }

                }
                document.close();
            }
            //osw.write(xmlStr.toString());
            osw.write("\r\n");
            osw.write("\r\n");
            //osw.write(jsonStr.toString());
            osw.flush();
            osw.close();
            fileOutputStream.close();

        }catch (Exception e){
            e.printStackTrace();
        }
    }

    //去掉特殊字符
    private String getRealField(String str){
        if(str==null|| str.equals("")){
            return str;
        }
        String regEx="[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        String s =m.replaceAll("").trim();
        return s;
    }
    /**
     * 获取段落内容
     *
     * @param paragraph
     */
    private void getParagraphText(XWPFParagraph paragraph) {
        // 获取段落中所有内容
        List<XWPFRun> runs = paragraph.getRuns();
        if (runs.size() == 0) {
            System.out.println("按了回车（新段落）222222");
            return;
        }
        StringBuffer runText = new StringBuffer();
        for (XWPFRun run : runs) {
            runText.append(run.text());
        }
        if (runText.length() > 0) {
            runText.append("，对齐方式222222：").append(paragraph.getAlignment().name());
            System.out.println(runText);
        }
    }

    private String getTableCellText(XWPFParagraph paragraph) {
        // 获取段落中所有内容
        List<XWPFRun> runs = paragraph.getRuns();
        if (runs.size() == 0) {
            return "";
        }
        StringBuffer runText = new StringBuffer();
        for (XWPFRun run : runs) {
            runText.append(run.text());
        }
        //System.out.println(runText);

        return runText.toString();
    }

    /**
     * 获取表格内容
     *
     * @param table
     */
    private String getTabelText(XWPFTable table,String tablename,String protocol) throws Exception{
        List<XWPFTableRow> rows = table.getRows();

        int x=0;
        StringBuffer ceateSql=new StringBuffer("create table HIIP.tablename(");
        StringBuffer commonSql=new StringBuffer("");
        StringBuffer xmlStr=new StringBuffer("");
        StringBuffer jsonStr=new StringBuffer("");
        String s1="";
        String s2="";
        String s3="";
        String s4="";
        int index=3;
        for (XWPFTableRow row : rows) {
            if(x==0){
                List<XWPFTableCell> cells = row.getTableCells();
                if(cells.size()<3){
                    continue;
                }
                x++;

                for(int i=1;i<4;i++){
                    List<XWPFParagraph> paragraphType = cells.get(i).getParagraphs();//取字段类型，第2个
                    String ftype=getTableCellText(paragraphType.get(0));//
                    if(ftype.equals("字段描述") || ftype.equals("数据元名称") || ftype.equals("字段名称")){
                        index=i;
                    }
                }
                continue;
            }
            List<XWPFTableCell> cells = row.getTableCells();

            List<XWPFParagraph> ycpar = cells.get(index).getParagraphs();//取第3个单元格中的值
            String ycfield=getTableCellText(ycpar.get(0));//

            //获取字段
            List<XWPFParagraph> paragraphs = cells.get(0).getParagraphs();//取第一个单元格中的值
            String path=getTableCellText(paragraphs.get(0));//
            if(path==null || path.equals("")){
                continue;
            }
            int i=0;
            if(ycfield.indexOf("医疗机构组织机构代码")>-1){
                if(!s1.equals("")){
                    System.out.println("有两个组织机构");
                }
                s1=path;

                i=1;
            }else if(ycfield.indexOf("住院号")>-1 || ycfield.indexOf("门诊号")>-1 || ycfield.indexOf("专项档案编号")>-1){
                //xmlStr.append(path).append("?");
                s2=path;
                i=1;
            }else if(ycfield.indexOf("住院次数")>-1 || ycfield.indexOf("城乡居民健康档案编号")>-1){
                //xmlStr.append(path).append("。");
                s3=path;
                i=1;
            }else if(ycfield.indexOf("病案号")>-1 || ycfield.indexOf("记录表单编号")>-1){
                //xmlStr.append(path).append("号");
                if(!s4.equals("")){
                    System.out.println(tablename+"有两个单号"+protocol+":"+ycfield);
                }
                s4=path;
                i=2;
            }

        }
        if(!s1.equals("")){
            xmlStr.append(s1).append(",");
        }
        if(!s2.equals("")){
            xmlStr.append(s2).append("?");
        }
        if(!s3.equals("")){
            xmlStr.append(s3).append(".");
        }
        if(!s4.equals("")){
            xmlStr.append(s4);
        }
        return xmlStr.toString();
        //osw.write(ceateSql.toString()+"\r\n");
        //osw.write(commonSql.toString());
        //osw.write("\r\n");


    }

    private String getSpecificationWord(String word){
        if(word.length()>1){
            return word.substring(0, 1).toUpperCase()+word.substring(1);
        }else {
            return word;
        }
    }
}
